import PySimpleGUI as sg
import cv2
import numpy as np
import glob
import os

# 鼠标回调函数
def drag_and_zoom(event, x, y, flags, param):
    global drag_start, zoom_level, img_resized, img_original

    # 拖拽开始，记录起始点坐标
    if event == cv2.EVENT_LBUTTONDOWN:
        drag_start = (x, y)

    # 拖拽结束，更新图像显示区域
    if event == cv2.EVENT_LBUTTONUP:
        dx = x - drag_start[0]
        dy = y - drag_start[1]
        drag_start = None
        update_view(dx, dy)

    # 滚轮滚动，更新缩放级别
    if event == cv2.EVENT_MOUSEWHEEL:
        if flags > 0:
            if zoom_level < 5:
                zoom_level += 1
        else:
            if zoom_level > 1:
                zoom_level -= 1
        update_view(0, 0)

# 更新图像显示区域
def update_view(dx, dy):
    global img_resized, img_original, zoom_level, view_start

    # 更新显示区域的起始点坐标
    view_start[0] -= dx
    view_start[1] -= dy

    # 根据缩放级别调整图像大小
    img_resized = cv2.resize(img_original, None, fx=zoom_level, fy=zoom_level)

    # 显示图像
    show_image()

# 显示图像
def show_image():
    global img_resized, view_start

    # 获取显示区域
    view_area = img_resized[view_start[1]:view_start[1]+512, view_start[0]:view_start[0]+512]

    # 显示图像
    cv2.imshow('Image', view_area)

# 主函数
def main():
    layout = [
        [sg.Text('图像路径'), sg.Input(key='-IN-'), sg.FolderBrowse()],
        [sg.Text('裁切尺寸'), sg.Input(default_text='512,512', key='-SIZE-')],
        [sg.Text('保存格式'), sg.InputCombo(['png', 'jpg'], size=(20, 1))],
        [sg.Text('保存路径'), sg.Input(key='-OUT-'), sg.FolderBrowse()],
        [sg.Button('开始'), sg.Button('退出')]
    ]

    window = sg.Window('图像处理工具', layout)

    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED or event == '退出':
            break
        if event == '开始':
            process_images(values['-IN-'], values['-SIZE-'], values['-OUT-'])

    window.close()

# 图像处理函数
def process_images(in_folder, size, out_folder):
    images = glob.glob(os.path.join(in_folder, '*'))
    for image_path in images:
        global img_original, img_resized, zoom_level, view_start, drag_start

        # 初始化全局变量
        img_original = cv2.imread(image_path)
        img_resized = img_original.copy()
        zoom_level = 1
        view_start = [0, 0]
        drag_start = None

        # 创建窗口并设置鼠标回调函数
        cv2.namedWindow('Image')
        cv2.setMouseCallback('Image', drag_and_zoom)

        # 显示图像
        show_image()

        # 等待用户按键
        while True:
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == 13:  # Enter key
                # 裁剪图像
                crop_image = img_resized[view_start[1]:view_start[1]+512, view_start[0]:view_start[0]+512]
                # 保存图像
                cv2.imwrite(os.path.join(out_folder, os.path.basename(image_path)), crop_image)
                # 跳出循环，处理下一张图像
                break

        cv2.destroyAllWindows()

if __name__ == '__main__':
    main()
